import { Physics, type Types, Scene, Math } from "phaser";
import type { Main } from "../Main";

export class Pipe extends Physics.Arcade.Sprite {
    // 小鸟是否通过
    isPass: boolean = false;
    scene: Main = null;

    constructor(scene: Main, x: number, frame: number) {
        // 根据水管类型生成随机y坐标
        let y = frame == 0 ? Math.Between(-60, 0) : Math.Between(400, 460);
        // 创建对象
        super(scene, x, y, "pipe", frame);
        this.scene = scene;
        scene.add.existing(this);
        scene.physics.add.existing(this);

        // 设置属性
        this.setOrigin(0, 0.5);
    }
    preUpdate(time: number, delta: number) {
        super.preUpdate(time, delta);
        // 水管走到头，重置
        if (this.body.x < -54) {
            let x = this.scene.cameras.main.width;
            let y = this.frame.name == "0" ? Math.Between(-50, 10) : Math.Between(390, 450);
            this.body.reset(x, y);
            this.isPass = false;
            this.setVelocityX(-200);
        }
        // 上水管经过小鸟，得分
        if (this.frame.name == "0" && this.body.x <= 29 && this.isPass == false) {
            this.isPass = true;
            this.scene.scoreAdd();
        }
    }
}
